using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class Grid : MonoBehaviour
{
    public int xSize, ySize;
    Mesh mesh;

    Vector3[] vertices;
    Vector2[] uv;
    Vector4[] tangents;
    int[] triangles;

    void Awake()
    {
        GetComponent<MeshFilter>().mesh = mesh = new Mesh();
        mesh.name = "Procedural Grid";

        vertices = new Vector3[(xSize + 1) * (ySize + 1)];
        uv = new Vector2[vertices.Length];
        tangents = new Vector4[vertices.Length];
        triangles = new int[xSize * ySize * 6];

        Generate();
        mesh.RecalculateNormals();
    }

    void Generate()
    {
        for (int y = 0, v = 0; y <= ySize; y++)
        {
            for (int x = 0; x <= xSize; x++, v++)
            {
                vertices[v] = new Vector3(x, y, 0);
                uv[v] = new Vector2(1f * x / xSize, 1f * y / ySize);
                tangents[v] = new Vector4(1f, 0f, 0f, 1f);
            }
        }

        mesh.vertices = vertices;
        mesh.tangents = tangents;
        mesh.uv = uv;

        for (int y = 0, v = 0, t = 0; y < ySize; y++, v++)
        {
            for (int x = 0; x < xSize; x++, v++, t += 6)
            {
                triangles[t] = v;
                triangles[t + 1] = triangles[t + 4] = v + xSize + 1;
                triangles[t + 2] = triangles[t + 3] = v + 1;
                triangles[t + 5] = v + xSize + 2;
            }
        }

        mesh.triangles = triangles;
    }

    void OnDrawGizmos()
    {
        if (Application.isPlaying)
        {
            foreach (var pos in vertices)
            {
                Gizmos.DrawSphere(pos, .1f);
            }
        }
    }
}